<template>
  <div class="login-container">
    <el-card class="login-card">
      <h3 class="login-title">港口堆存费管理系统</h3>
      <el-form ref="formRef" :model="loginForm" :rules="loginRules" label-width="80px" class="login-form">
        <el-form-item label="用户名" prop="id">
          <el-input v-model="loginForm.id" placeholder="请输入用户id"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item class="login-button">
          <el-button type="primary" @click="onSubmit">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { login } from '~/api/login.js';
import { useRouter } from 'vue-router'; // 正确引入 vue-router 的 useRouter

const loginForm = reactive({
  id: '',
  password: ''
});

const loginRules = reactive({
  id: [{ required: true, message: '用户id不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
});

const formRef = ref(null);
const router = useRouter(); // 获取路由对象

const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (!valid) {
      return false;
    }
    login(loginForm.id, loginForm.password)
    .then(res => {
    if (res.data && res.data.code=='200') {
        console.log('Login successful:', res.data);
        router.push('/home'); // 登录成功后跳转到 '/home' 页面
    } else {
        console.error('Login failed. Unexpected response:', res.data);
        // 可以在界面上显示登录失败的消息或其他处理
    }
})
      .catch(err => {
        console.error(err.response.data);
      });
  });
};
</script>


<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url('https://preview.cloud.189.cn/image/imageAction?param=A046A3272027AC1C39B49F8D0E331EDF04571377103AF0DF4001A2F5E49E2F7F31A1911777FBD5452AC50A38B763193F165AE17CFF2F28D3D60C2DA7E6E3A816E0BD8A3580B22F8DB639E7C18340CA1501279FA8081871AE91C2BCEACE4657771DC39E644FB6C944AAEA924920E3F03083E2A96B');
  /* 背景图片路径 */
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.login-card {
  width: 400px;
  text-align: center;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.8);
  /* 设置登录框背景色及透明度 */
  position: relative;
  border-radius: 10px;
}

.login-title {
  font-size: 24px;
  margin-bottom: 20px;
}

.login-form {
  width: 80%;
  margin: 0 auto;
}

.login-button {
  margin-top: 20px;
  width: 100%;
}
</style>
